// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
const $ = _.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  // db.userinfo.aggregate([{ "$lookup": { "localField": "id", "from": "rank", "foreignField": "userid", "as": "rankinfo" } },
  //  { "$sort": { "rankinfo.point": -1 } },
  //   { "$match": { "rankinfo.week": "2021020" } }]);
  let week = event.week || 2021020,
  skip = event.skip || 0,
  limit = event.limit || 20;
  return await db.collection('ad_idol').aggregate()
    // .lookup({
    //   from: "ad_rank_week",
    //   localField: "_id",
    //   foreignField: "idol_id",
    //   as: "rankList"
    // })
      .lookup({
      from: "ad_rank_week",
      let: {
        // order_book: '$book',
        // order_quantity: '$quantity'
        // hasdel: '$hasdel',
        idol_id: '$_id'
      },
      pipeline: $.pipeline()
        .match(_.expr($.and([
          // $.eq(['$title', '$$order_book']),
          // $.gte(['$stock', '$$order_quantity'])
          // $.eq([0, '$$hasdel']),
          $.eq(['$idol_id', '$$idol_id']),
          $.eq(['$week', week])
        ])))
        .project({
          _id: 0,
          week: 1,
          votes: 1
        })
        .done(),
      as: 'rank',
    })
    // .match({
    //   "rankList.week": { $exists: true, $not: { $type: "array" }, $type: "object" }
    // })
    .sort({
      "rank.votes": -1
    })
    .unwind({
      path: '$rank',
      preserveNullAndEmptyArrays: true
    })
    // .match({
    //   "rankList.week": 2021020//{ $exists: true, $not: { $type: "array" }, $type: "object" }
    // })
    // .replaceRoot({
    //   newRoot: $.mergeObjects([$.arrayElemAt(['$rankList', 0]), '$$ROOT'])
    // })
    // .project({
    //   rankList: 0,
    //   votes1: "$rankList[0].votes"
    // })
    .skip(skip)
    .limit(limit)
    .end()
  // .then(res => console.log(res))
  // .catch(err => console.error(err))
}